/*
 * #%L
 * SwiftUIDataAccessLayer
 * $Id:$
 * $HeadURL:$
 * %%
 * Copyright (C) 2011 - 2012 Linkwithweb
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/gpl-3.0.html>.
 * #L%
 */
/**
 * 
 */
package com.linkwithweb.products.swiftui.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;

import com.linkwithweb.products.swiftui.context.SystemContext;
import com.linkwithweb.products.swiftui.dataobject.FrameworkApplication;
import com.linkwithweb.products.swiftui.utils.FreeMarkerEngine;
import com.linkwithweb.products.swiftui.utils.ServiceLocator;

/**
 * @author ashwin kumar
 * 
 */
public abstract class AbstractDAOImpl {
	protected static Map<String, JdbcTemplate> templateMap = new ConcurrentHashMap<String, JdbcTemplate>();
	protected static List<String> systemColumns = new ArrayList<String>();
	{
		if (systemColumns.isEmpty()) {
			systemColumns.add("IS_ACTIVE");
			systemColumns.add("IDENTIFIER");
			systemColumns.add("IDENTIFIER_ROLE");
			systemColumns.add("CREATED_BY");
			systemColumns.add("CREATED_DATE");
			systemColumns.add("MODIFIED_BY");
			systemColumns.add("MODIFIED_DATE");
		}
	}

	/**
	 * @param dataSourceTemplateName
	 * @return
	 */
	public JdbcTemplate getJdbcTemplate(String dataSourceTemplateName) {
		if (StringUtils.equalsIgnoreCase(dataSourceTemplateName, "jdbcTemplate")
				|| StringUtils.equalsIgnoreCase(dataSourceTemplateName, "frameworkJdbcTemplate")) {
			return (JdbcTemplate) ServiceLocator.getService("jdbcTemplate");
		}
		if (templateMap.get(dataSourceTemplateName) == null) {
			templateMap.put(dataSourceTemplateName, (JdbcTemplate) ServiceLocator.getService(dataSourceTemplateName));
		}
		return templateMap.get(dataSourceTemplateName);
	}

	/**
	 * @param paramName
	 * @return
	 */
	protected String getRequestParamter(String paramName) {
		String paramString = "${GlobalContext.requestContext.requestWrapper." + paramName + "}";
		try {
			return FreeMarkerEngine.getInstance().evaluateString(paramString);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * Append Conditions by Userid/Role/Identifier
	 * 
	 * @param sql
	 * @return
	 */
	protected void appendSystemColumnNames(StringBuffer queryString) {
		appendSystemColumnNames(queryString, null);
	}

	/**
	 * Append Conditions by Userid/Role/Identifier
	 * 
	 * @param paramNames
	 *            TODO
	 * @param sql
	 * 
	 * @return
	 */
	protected void appendSystemColumnNames(StringBuffer queryString, List<String> paramNames) {
		if (paramNames != null) {
			paramNames.addAll(systemColumns);
		} else {
			for (String columnName : systemColumns) {
				queryString.append(",").append(columnName);
			}
		}
	}

	/**
	 * @param genericQuery
	 * @param arguments
	 * @param paramNames
	 *            TODO
	 */
	protected void appendSystemColumnValues(StringBuffer genericQuery, List arguments, List<String> paramNames) {

		FrameworkApplication app = SystemContext.getInstance().getUserContext().getFrameworkUser()
				.getListOfApplications().get(0);

		if (paramNames == null) {
			genericQuery.append(",?,?,?,?,?,?,?)");

			arguments.add("1");
			arguments.add(app.getAppId());
			arguments.add("ALL");
			arguments.add(SystemContext.getInstance().getUserContext().getFrameworkUser().getUniqueKey());
			arguments.add(new Date());
			arguments.add(SystemContext.getInstance().getUserContext().getFrameworkUser().getUniqueKey());
			arguments.add(new Date());
		} else {
			arguments.add("1");
			arguments.add(app.getAppId());
			arguments.add("ALL");
			arguments.add(SystemContext.getInstance().getUserContext().getFrameworkUser().getUniqueKey());
			arguments.add(new Date());
			arguments.add(SystemContext.getInstance().getUserContext().getFrameworkUser().getUniqueKey());
			arguments.add(new Date());

			genericQuery.append(" SET ");
			boolean firstValue = true;
			for (String paramName : paramNames) {
				if (!firstValue) {
					genericQuery.append(",");
				}
				firstValue = false;
				genericQuery.append(paramName).append("=?");
			}
		}
	}

	/**
	 * @param tableName
	 * @param schemaName
	 * @return
	 */
	protected static String getDatasourceName(String tableName, String schemaName) {
		String dataSourceName = "frameworkJdbcTemplate";

		if (!(StringUtils.containsIgnoreCase(tableName, "FRM_") && StringUtils.containsIgnoreCase(schemaName,
				"AUTOMATA"))) {
			dataSourceName = SystemContext.getInstance().getUserContext().getFrameworkUser().getListOfApplications()
					.get(0).getAppId();
		}
		return dataSourceName;
	}

	public static void main(String[] args) {
		System.out.println(getDatasourceName("frm_test", "automata"));
	}

	/**
	 * @return
	 */
	protected String getUniqueString() {
		String returnString = "";
		Date newDate = new Date();
		try {

			SimpleDateFormat formatter;
			formatter = new SimpleDateFormat("yyyyMMddhhmmss");
			java.util.Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
			formatter.setCalendar(cal);

			returnString = formatter.format(newDate);
			// System.out.println(formatter.format(newDate));
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}

		return returnString;
	}

	/**
	 * @return
	 */
	protected String getDateString() {
		String returnString = "";
		Date newDate = new Date();
		try {

			SimpleDateFormat formatter;
			formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			java.util.Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
			formatter.setCalendar(cal);

			returnString = formatter.format(newDate);
			// System.out.println(formatter.format(newDate));
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}

		return returnString;
	}
}
